package com.solocredit.finance.ui.user.act

import android.annotation.SuppressLint
import android.app.PendingIntent
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
import android.text.Editable
import android.text.SpannableString
import android.text.Spanned
import android.text.TextWatcher
import android.text.style.ForegroundColorSpan
import android.text.style.StyleSpan
import android.text.style.UnderlineSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.activity.result.IntentSenderRequest
import androidx.activity.result.contract.ActivityResultContracts
import com.google.android.gms.auth.api.identity.GetPhoneNumberHintIntentRequest
import com.google.android.gms.auth.api.identity.Identity
import com.solocredit.finance.R
import com.solocredit.finance.app.MyApp
import com.solocredit.finance.base.utils.ImageUtil
import com.solocredit.finance.base.utils.TitleBarUtil
import com.solocredit.finance.base.utils.helper.ActivityStackManager
import com.solocredit.finance.base.utils.log.MullaLog
import com.solocredit.finance.config.MullaConfigs
import com.solocredit.finance.databinding.ActMullaUserLoginBinding
import com.solocredit.finance.http.HttpHelper
import com.solocredit.finance.mvp.MvpAct
import com.solocredit.finance.ui.MullaPaPoyAct
import com.solocredit.finance.ui.main.act.MullaMainAct
import com.solocredit.finance.ui.user.impl.MullaLoginPresenterImpl
import com.solocredit.finance.ui.user.view.IMullaLoginView
import com.solocredit.finance.utils.event.MullaBehaviorTracker
import com.solocredit.finance.utils.event.MullaEventType
import com.solocredit.finance.utils.helper.MullaCustomConfigsHelper
import com.solocredit.finance.utils.helper.SharedHelper
import com.solocredit.finance.weight.input.TimeStampEditText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject


/**
 * MullaFlow
 * @Author wwdeng
 * @CreateTime: 2024/7/26 13:40
 * @Annotation：登录
 */
class MullaUserLoginAct: MvpAct<IMullaLoginView, MullaLoginPresenterImpl>(),IMullaLoginView{
    lateinit var binding: ActMullaUserLoginBinding

    override fun createPresenter(): MullaLoginPresenterImpl {
        return MullaLoginPresenterImpl(this)
    }

    override fun getMullaRootView(): View {
        binding = ActMullaUserLoginBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initMullaView() {
        TitleBarUtil.setStatusBarLightMode(this, false)
        setMullaTitleBarVisibility(View.VISIBLE)
        setMullaTitleBarColor(Color.parseColor("#FF8027FF"))
        setMullaBackBtnVisibility(View.GONE)
        setMullaTextTitleVisibility(View.INVISIBLE)
        setMullaRightBtnRes(R.mipmap.mulla_kefu_icon)
        if (MullaConfigs.isTanz()){
            setMullaLanguageBtnRes(R.mipmap.mulla_language_choose_white_icon)
        }

        //关闭所有页面
        ActivityStackManager.finishAllActivity(MullaUserLoginAct::class.java)
        checkMullaLoginBtnState()

        //用户使用条款
        val termsUseUrl = MullaCustomConfigsHelper.getMullaTermsUseLink()
        if (termsUseUrl.isEmpty()){
            binding.termsUseLayout.visibility = View.GONE
        }
        binding.editMobile.visibility = View.VISIBLE
        binding.textMaskMobile.visibility = View.VISIBLE
    }

    override fun initMullaListener() {
        //切换语言
        rootViewBinding.ivLanguage.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LANGUAGE,"Login Page")
            showMullaLanguageDialog("Login Page", isCancel = true, isCancelTouch = true, onSelectCallback = {
            })
        }
        //联系客服
        rootViewBinding.ivFun.setOnClickListener {
            showMullaKefuDialog("Login Page")
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_CUSTOMER,"Login Page")
        }

        binding.textMaskMobile.setOnClickListener {
            binding.mobileLayout.setBackgroundResource(R.drawable.mulla_radius_frame_ff8027ff_12)
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_USER_LOGIN_SELF_MOBILE, "")
            getMullaSelfPhoneNumber()
        }
        binding.editMobile.setInputFocusChangeListener(object : TimeStampEditText.IInputFocusChangeListener {
            override fun onFocusChange(v: View, hasFocus: Boolean) {
                when(hasFocus){
                    true -> {
                        binding.mobileLayout.setBackgroundResource(R.drawable.mulla_radius_frame_ff8027ff_12)
                    }
                    else -> {
                        binding.mobileLayout.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
                    }
                }
            }
            override fun onEditSubmitPointAction(v: View, remark: String) {
                HttpHelper.addMullaEventAction(MullaEventType.FORM.MULLA_FORM_LOGIN_MOBILE, remark)
            }
        })
        //电话号码入框监听
        binding.editMobile.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            }
            override fun afterTextChanged(s: Editable?) {
                checkMullaLoginBtnState()
            }
        })
        binding.editMobile.setOnEditorActionListener { v, actionId, event ->
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                binding.editMobile.clearFocus()
                true
            }
            false
        }

        //隐私政策切换
        binding.checkBoxPP.setOnCheckedChangeListener { _, isChecked ->
            checkMullaLoginBtnState()
            when (isChecked) {
                true -> {
                    HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LOGIN_PRIVACY_AGREE, "")
                }
                false -> {
                    HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LOGIN_PRIVACY_DENY, "")
                }
            }
        }

        //使用条款
        binding.checkBoxTOU.setOnCheckedChangeListener { _, isChecked ->
            checkMullaLoginBtnState()
            when (isChecked) {
                true -> {
                    HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LOGIN_TERMS_OF_USE_AGREE)
                }
                false -> {
                    HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LOGIN_TERMS_OF_USE_DENY)
                }
            }
        }

        //登录
        binding.btnLogin.setOnClickListener {
            HttpHelper.addMullaEventAction(MullaEventType.CLICK.MULLA_CLICK_LOGIN_NEXT, getMullaMobile())
            // TODO: login 批量埋点上报
            MullaBehaviorTracker.getInstance(MyApp.app).reportImmediately(null)
            onHideSoftInput(binding.editMobile)
            showMullaLoading(isTOuchOut = false, isCancel = true)
//            presenter.loginMullaAction(getMullaMobile(),getMullaCode(),"NO")
            presenter.loginMullaNoCodeAction(getMullaMobile())
        }

        //协议
        binding.textPrivacyPolicy.setOnClickListener {
            val showTitle = getString(R.string.privacy_policy_title)
//            val linkUrl = "https://www.vistafinance.net/pri.html"
            val linkUrl = MullaCustomConfigsHelper.getMullsPrivacyPolicyLink()
            MullaPaPoyAct.start(this,showTitle, linkUrl)
        }

        //用户使用条款
        binding.textTermsOfUse.setOnClickListener {
            val showTitle = getString(R.string.terms_of_use)
            val linkUrl = MullaCustomConfigsHelper.getMullaTermsUseLink()
            MullaPaPoyAct.start(this,showTitle, linkUrl)
        }
    }

    @SuppressLint("SetTextI18n")
    override fun initMullaData() {
        binding.textZoneCode.text = "+${SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE_CODE)}"
        binding.textZoneCode.paint.flags = Paint.UNDERLINE_TEXT_FLAG//下划线
        binding.textZoneCode.paint.isAntiAlias = true//抗锯齿

        val colorSpan = ForegroundColorSpan(Color.parseColor("#FF222222"))
        val underlineSpan = UnderlineSpan()
        val styleSpan = StyleSpan(Typeface.BOLD)

        val showText = String.format(getString(R.string.login_privacy_policy),getString(R.string.privacy_policy_title))
        val spString = SpannableString(showText)
        val start = showText.indexOf(getString(R.string.privacy_policy_title))
        spString.setSpan(colorSpan, start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(underlineSpan, start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spString.setSpan(styleSpan, start, showText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textPrivacyPolicy.text = spString

        val showTermsText = String.format(getString(R.string.login_privacy_policy),getString(R.string.terms_of_use))
        val spTermsString = SpannableString(showTermsText)
        val startTerms = showTermsText.indexOf(getString(R.string.terms_of_use))
        spTermsString.setSpan(colorSpan, startTerms, showTermsText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spTermsString.setSpan(underlineSpan, startTerms, showTermsText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        spTermsString.setSpan(styleSpan, startTerms, showTermsText.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        binding.textTermsOfUse.text = spTermsString

        //牌照信息
        val licenseInfo = MullaCustomConfigsHelper.getMullaLicenseInfo()
        if (licenseInfo == null){
            binding.licenseLayout.visibility = View.GONE
        } else {
            binding.licenseLayout.visibility = View.VISIBLE
            ImageUtil.instance?.loadImageUrl(this,binding.imgLicenseLogo, licenseInfo.optString("logo"))
            binding.textLicenseDesc.text = licenseInfo.optString("desc")
            binding.textLicenseValue.text = licenseInfo.optString("companyName")
        }
    }

    /**
     * 设置登录按钮状态
     */
    private fun checkMullaLoginBtnState() {
        if (binding.editMobile.hasFocus()){
            binding.mobileLayout.setBackgroundResource(R.drawable.mulla_radius_frame_ff8027ff_12)
        } else {
            binding.mobileLayout.setBackgroundResource(R.drawable.mulla_radius_frame_ffe0dbee_12)
        }
        binding.editMobile.setTextColor(Color.parseColor("#000000"))
        binding.wrongLayout.visibility = View.INVISIBLE
        if (binding.checkBoxPP.isChecked && binding.checkBoxTOU.isChecked && getMullaMobile().isNotEmpty()) {
            binding.btnLogin.isEnabled = true
        } else {
            binding.btnLogin.isEnabled = false
        }
    }

    override fun getMullaMobile(): String {
        return binding.editMobile.text.toString().trim()
    }

    override fun getMullaCode(): String {
        return "0000"
    }

    override fun showSenCodeSuccess() {
    }

    override fun showMullaLoginFailure(data: JSONObject) {
        binding.mobileLayout.setBackgroundResource(R.drawable.mulla_login_wrong_mobile)
        binding.editMobile.setTextColor(Color.parseColor("#FFF55555"))
        binding.wrongLayout.visibility = View.VISIBLE
    }

    override fun showMullaMainPage() {
        onIntent(MullaMainAct::class.java)
        finish()
    }

    /**
     * 获取本机手机号码
     */
    private fun getMullaSelfPhoneNumber(){
        val request: GetPhoneNumberHintIntentRequest = GetPhoneNumberHintIntentRequest.builder().build()
        Identity.getSignInClient(this)
            .getPhoneNumberHintIntent(request)
            .addOnSuccessListener { result: PendingIntent ->
                try {
                    phoneNumberHintIntentResultLauncher.launch(IntentSenderRequest.Builder(result).build())
                } catch (e: Exception) {
                    MullaLog.e("Launching the PendingIntent failed")
                    showMullaEditMobile()
                }
            }
            .addOnFailureListener {
                MullaLog.e("Phone Number Hint failed : OnFailureListener")
                showMullaEditMobile()
            }
    }

    private val phoneNumberHintIntentResultLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        try {
            var phoneNumber = Identity.getSignInClient(this).getPhoneNumberFromIntent(result.data)
            MullaLog.e(">>>>>>>>>>>>>>>>>>>>>>>Phone Number $phoneNumber")
            HttpHelper.addMullaEventAction(MullaEventType.FORM.MULLA_FORM_USER_LOGIN_SELF_MOBILE, phoneNumber)
            //时区区号
            val zoneCode = "+${SharedHelper.getMullaSPString(SharedHelper.MULLA_SPKEY.MULLA_TIMEZONE_CODE)}"
            phoneNumber = phoneNumber.replace(zoneCode,"")
            binding.editMobile.setText(phoneNumber)
            binding.editMobile.visibility = View.VISIBLE
            binding.textMaskMobile.visibility = View.GONE
            binding.editMobile.requestFocus()
            binding.editMobile.setSelection(getMullaMobile().length)
        } catch(e: Exception) {
            MullaLog.e("Phone Number Hint failed：${e.message}")
            showMullaEditMobile()
        }
    }

    /**
     * 显示手机号码输入框
     */
    private fun showMullaEditMobile(){
        binding.editMobile.visibility = View.VISIBLE
        binding.textMaskMobile.visibility = View.GONE

        launch(Dispatchers.Main){
            delay(200)
            binding.editMobile.requestFocus()
            onShowSoftInput(binding.editMobile)
            binding.editMobile.setSelection(getMullaMobile().length) // 将光标设置到文本末尾
        }
    }

    override fun onStart() {
        super.onStart()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LOGIN_START, "")
    }

    override fun onDestroy() {
        super.onDestroy()
        HttpHelper.addMullaEventAction(MullaEventType.PAGE.MULLA_PAGE_LOGIN_END, "")
    }
}